import java.util.ArrayList;

public class Graph {
	protected ArrayList<Vertex> vertices;

	public Graph() {
		vertices = new ArrayList<Vertex>();
	}

	public ArrayList<Vertex> getVertices() {
		return vertices;
	}

	public void putEdge(String sourceName, String destinationName, int edgeValue) {
		Vertex source = getVertex(sourceName);
		Vertex destination = getVertex(destinationName);
		if (source != null && destination != null) {
			if (destination.getEdge(source) == null) {
				Edge e = new Edge(source, destination, edgeValue);
				destination.addIncomingEdge(e);
				source.addOutgoingEdge(e);
			}
		}
	}

	public void removeEdge(String sourceName, String destinationName) {
		Vertex source = getVertex(sourceName);
		Vertex destination = getVertex(destinationName);
		if (source != null && destination != null) {
			Edge e1 = null;
			for (Edge e : destination.getInComingEdges()) {
				if (e.getStartVertex().equals(source)) {
					e1 = e;
					break;
				}
			}
			destination.removeEdge(e1);
			source.removeEdge(e1);
		}
	}

	public void putVertex(String vertexName) {
		if (getVertex(vertexName) == null) {
			vertices.add(new Vertex(vertexName));
		}
	}

	public Vertex getVertex(String name) {
		Vertex vertex = null;
		for (Vertex v : vertices) {
			if (v.getName().equalsIgnoreCase(name)) {
				vertex = v;
				break;
			}
		}
		return vertex;
	}

	public void removeVertex(String vertexName) {
		Vertex vertex = getVertex(vertexName);
		if (vertex != null) {
			for (Vertex v : vertices) {
				ArrayList<Edge> e1 = new ArrayList<Edge>();
				for (Edge e : v.getInComingEdges()) {
					if (e.getStartVertex().equals(vertex)) {
						e1.add(e);
					}
				}
				for (Edge remove : e1) {
					v.removeEdge(remove);
				}
			}
			vertices.remove(vertex);
		}
	}

	public String toString() {
		String receiving = "";
		for (Vertex v : vertices) {
			receiving += v.toString() + " - ";
		}
		return receiving;
	}

}
